#!/usr/bin/env python3
"""
Analyze HTTP access log for a ~10-minute window.
Input: file path or stdin. Output: ip fourxx_count uri_variety sample_ua (Top5).
Assumes input already limited to about 10 minutes.
"""
import sys, re
from collections import defaultdict

def stream(fp):
    if fp:
        with open(fp, 'r', encoding='utf-8', errors='ignore') as f:
            for line in f:
                yield line
    else:
        for line in sys.stdin:
            yield line

pat = re.compile(r'^(\S+).*?"[A-Z]+ ([^ ]+) [^"]*"\s+([0-9]{3}).*?"[^"]*"\s*"([^"]*)"')

def main():
    path = sys.argv[1] if len(sys.argv) > 1 else None
    four = defaultdict(int)
    uris = defaultdict(set)
    ua = {}
    for line in stream(path):
        m = pat.search(line)
        if not m:
            continue
        ip, uri, status, useragent = m.group(1), m.group(2), m.group(3), m.group(4)
        if status.startswith('4'):
            four[ip] += 1
        if uri:
            uris[ip].add(uri)
        if useragent and ip not in ua:
            ua[ip] = useragent
    rows = [(ip, four[ip], len(uris[ip]), ua.get(ip, '')) for ip in four]
    rows.sort(key=lambda x: (-x[1], x[0]))
    for ip, cnt, ucnt, uastr in rows[:5]:
        print(f"{ip}\t{cnt}\t{ucnt}\t{uastr}")

if __name__ == '__main__':
    main()
